var mobx = require('../libs/mobx');
var observable = require('../libs/mobx').observable;
var extendObservable = require('../libs/mobx').extendObservable;
let network = require('../utils/network.js')
var action = mobx.action;

// 地址管理item
var AddrItem = function(json) {
  extendObservable(this, {
    recievName: json.recievName,
    phoneNum: json.phoneNum,
    detailAddress: json.detailAddress,
    fullAddress: json.fullAddress,
    districtAddress: json.districtAddress,
    isDefault: json.isDefault,
    userId: false,
    id: json.id
  })
}

// 地址管理容器store
var AddrMgrStore = function() {
  extendObservable(this, {
    addrList: [],
    activeAddr: null
  });

  this.refreshList = action(function() {
      var that = this;
    network.requestLoading('mp/client/deliveryAddress/list', {
        size: 10,
        pageNo: 0
      }, '', function(res) {
        //res就是我们请求接口返回的数据
        that.addrList = res.data.content.map(json => {
          return new AddrItem(json);
        });
        //设置默认地址
        if (that.activeAddr==null){
         that.addDef();
       }
      }, function() {
      
      })
    }),

    this.addDef = function() {
      for (var addr of this.addrList) {
        if (addr.isDefault == 1) {
          this.activeAddr = addr;
          return;
        }
        this.activeAddr = addr ;
      }

    }

  this.findAddById = function(id) {
      for (var i = 0; i < this.addrList.length; i++) {
        var addr = this.addrList[i];
        if (addr.id == id) {
          return addr;
        }
      }
    },

    this.setActiveAddr = action(function(id) {
      this.activeAddr = this.findAddById(id);
    })

  this.delAddr = action(function(id) {
    var self = this;
    network.requestLoading('mp/client/deliveryAddress/delete', {
      addressId: id
    }, '正在删除...', function(res) {
      self.refreshList();
    }, function() {
      wx.showToast({
        title: '删除失败!',
      })
    })
  })

  this.setDef = action(function(id) {
    var self = this;
    network.requestLoading('mp/client/deliveryAddress/setDefault', {
      addressId: id,
      isDefault: 1
    }, '正在设置...', function(res) {
      self.refreshList();
    }, function() {
      wx.showToast({
        title: '操作失败!',
      })
    })
  })
}

module.exports = {
  default: new AddrMgrStore(),
}